package com.ygk.bluepath.core.View;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.ygk.bluepath.R;
import com.ygk.bluepath.bean.LocationBean;
import com.ygk.bluepath.core.BActivity;
import com.ygk.bluepath.core.Presenter.ReCorderPresenter;
import com.ygk.bluepath.service.LBSService;

import java.util.List;

import utils.GpsUtil;
import utils.LogUtils;
import utils.ServiceUtil;
import utils.ui.view.DialogWithOutView;


public class RecorderActivity extends BActivity implements OnClickListener, AdapterView.OnItemSelectedListener, RecorderView {

    @ViewInject(R.id.et_flagid)
    private EditText et_flagId;
    @ViewInject(R.id.sp_type)
    private Spinner spinner_type;

    @ViewInject(R.id.tv_lng)
    private EditText tv_lng;
    @ViewInject(R.id.tv_lat)
    private EditText tv_lat;

    @ViewInject(R.id.bt_commit)
    private Button bt_commit;
    @ViewInject(R.id.bt_show)
    private Button bt_show;
    @ViewInject(R.id.bt_test)
    private Button bt_test;

    private ReCorderPresenter reCorderPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder);
        ViewUtils.inject(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 判断GPS是否正常启动
        if (!GpsUtil.isGpsOpen(this)) {
            tt("请开启GPS导航..."); // 返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 0);
            return;
        }
    }

    private void init() {
        // TODO Auto-generated method stub

        reCorderPresenter = new ReCorderPresenter(this, this);
        reCorderPresenter.setViewTiTle("记录位置信息");

        // 建立数据源
        String[] mItems = getResources().getStringArray(R.array.locationTypeArray);
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_record_type, mItems);
        //绑定 Adapter到控件
        spinner_type.setAdapter(adapter);
        spinner_type.setOnItemSelectedListener(this);
    }

    @OnClick(value = {R.id.tv_back, R.id.bt_commit, R.id.bt_show, R.id.bt_test})
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Object obj = v.getTag();

        if (obj != null) {
            if (obj.toString().contains("Cus")) {
                String idString = obj.toString().substring(3);
                try {
                    int cusId = Integer.parseInt(idString);

                    LocationBean lbdel = reCorderPresenter.getLocationById(cusId);
                    if (lbdel != null) {
                        dlwv.dismiss();
                        dlwv = null;
                        custShowDel(lbdel);
                    } else {
                        tt("数据查询失败");
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                }

            }
            ;
        }

        switch (v.getId()) {

            case R.id.tv_back:
                finish();
                break;
            case R.id.bt_commit:
                String flagString = et_flagId.getText().toString();

                if (flagString.isEmpty()) {
                    tt("请填写：" + getResources().getString(R.string.location_flagid));
                    return;
                }

                lbBean.setFlagId(flagString);
                reCorderPresenter.saveLocation(lbBean);
                tt(getResources().getString(R.string.save_seccuss));

                break;
            case R.id.bt_show:
                reCorderPresenter.showRecords();
                break;
            case R.id.bt_test:
                reCorderPresenter.deleteAll(LocationBean.class);
                reCorderPresenter.saveLocation(new LocationBean("浦软收费站", 121.594205, 31.21298, "浦软收费站", 0, 0));
                reCorderPresenter.saveLocation(new LocationBean("龙东大道1", 121.606290, 31.222283, "龙东大道1", 1, 0));
                reCorderPresenter.saveLocation(new LocationBean("龙东大道2", 121.622846, 31.224541, "龙东大道2", 1, 0));
                reCorderPresenter.saveLocation(new LocationBean("芳春路收费站", 121.633728, 31.218050, "芳春路收费站", 0, 0));
                reCorderPresenter.saveLocation(new LocationBean("祖冲之1", 121.623853, 31.213728, "祖冲之1", 1, 0));
                reCorderPresenter.saveLocation(new LocationBean("祖冲之2", 121.608151, 31.209751, "祖冲之2", 1, 0));
                tt("写入成功");

                break;
            default:
                break;
        }
    }

    private void custShowDel(final LocationBean lbdel) {
        // TODO Auto-generated method stub

        final DialogWithOutView dlwv = new DialogWithOutView(this, R.style.CustomDialog);

        View dlgView = dlwv.inflaterView(R.layout.dioalog_multisel, null);
        dlwv.setBgTransparent();
        ((TextView) dlwv.findViewById(R.id.tv_dialog_tt)).setText("请选择:");
        dlwv.findViewById(R.id.ll_dlg_multisel_click).setVisibility(View.VISIBLE);
        dlwv.findViewById(R.id.tv_close).setVisibility(View.GONE);
        LinearLayout ll_content = (LinearLayout) dlgView.findViewById(R.id.ll_content);

        TextView tv = new TextView(this);
        tv.setTextColor(Color.BLACK);
        tv.setText("是否删除数据(" + lbdel.getFlagId() + ")?");

        ll_content.addView(tv);

        dlwv.findViewById(R.id.bt_cancel).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dlwv.dismiss();
                    }
                });
        dlwv.findViewById(R.id.bt_ok).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dlwv.dismiss();
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                reCorderPresenter.deleteById(LocationBean.class,
                                        lbdel.getId());
                                showRecords();
                            }
                        });
                    }
                });
        dlwv.show();

    }

    DialogWithOutView dlwv;

    @Override
    public void showRecords() {
        if (dlwv == null) {
            dlwv = new DialogWithOutView(this, R.style.CustomDialog);
            dlwv.setBgTransparent();
        }
        View dlgView = dlwv.inflaterView(R.layout.dioalog_multisel, null);
        LinearLayout ll_content = (LinearLayout) dlgView.findViewById(R.id.ll_content);
        List<LocationBean> mlist = (List<LocationBean>) reCorderPresenter.getLocationAll(LocationBean.class);

        if (mlist == null) {
            tt("无数据");
            return;
        }
        LogUtils.i("mlist.size::" + mlist.size());
        for (LocationBean lbBean : mlist) {
            TextView tView = new TextView(this);
            tView.setMinHeight(20);
            tView.setTextSize(15);
            tView.setPadding(15, 15, 15, 15);
            tView.setText((lbBean.getLocationType() == 0 ? "收费站:" : "标识点:") + lbBean.getFlagId() + "——经纬度("
                    + lbBean.getLongitude() + "," + lbBean.getLatitude()
                    + ")");
            tView.setTag("Cus" + lbBean.getId());
            tView.setOnClickListener(this);
            tView.setTextColor(Color.BLACK);
            ll_content.addView(tView);
        }

        dlwv.findViewById(R.id.tv_close).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dlwv.dismiss();
                    }
                });
        dlwv.show();
    }

    @Override
    public void setLatitude(double latitude) {
        lbBean.setLatitude(latitude);
        tv_lat.setText(latitude + "");
    }

    @Override
    public void setLongitude(double longitude) {
        lbBean.setLongitude(longitude);
        tv_lng.setText(longitude + "");
    }

    @Override
    public void onStart() {
        super.onStart();

        reCorderPresenter.reGisterReceiver(this);
        if (ServiceUtil.isServiceWork(this, "com.ygk.bluepath.service.LBSService")) {
            LogUtils.e("com.ygk.bluepath.service.LBSService is running");
        } else {
            LogUtils.e("com.ygk.bluepath.service.LBSService is dead");
            startService();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        reCorderPresenter.unregisterReceiver();// 取消注册BroadcastReceiver

    }

    public void startService() {

        Intent i = new Intent(this, LBSService.class);
        startService(i);
        LogUtils.i("in startService method.");

    }

    public void stopService() {

        Intent i = new Intent(this, LBSService.class);
        stopService(i);
        LogUtils.i("in stopService method.");

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        stopService();
        super.onDestroy();
    }

    private LocationBean lbBean = new LocationBean();


    //private double xy=0.02;


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        lbBean.setLocationType(position);//0为收费站；1为标识点
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
